package com.my.oschina.adapter;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import com.my.oschina.MainActivity;
import com.my.oschina.bean.BlogList;
import com.my.oschina.common.AppFragmentPagerAdapter;
import com.my.oschina.fragment.InfoFragment;

/**
 * 资讯-PagerAdaper，继承了AppFragmentPagerAdapter，后者又继承了PagerAdapter
 */
public class NewsFragmentPagerAdapter extends AppFragmentPagerAdapter {

	private List<Fragment> fragmentList;
	private static int INFO_TAB_SIZE = 3;
	private String[] tagString = { "tag0", "tag1", "tag2" };

	public NewsFragmentPagerAdapter(InfoFragment fragment, ViewPager viewPager,
			FragmentManager fm, MainActivity activity,
			List<Fragment> fragmentList) {

		super(fm);
		this.fragmentList = fragmentList;

		fragmentList.add(0, fragment.getNewsChildFragment());
		fragmentList.add(1, fragment.getNewsBlogFragment(BlogList.TYPE_LATEST));
		fragmentList.add(2, fragment.getNewsBlogFragment(BlogList.TYPE_RECOMMEND));

		FragmentTransaction transaction = fragment.getChildFragmentManager()
				.beginTransaction();

		if (!fragmentList.get(0).isAdded()) {
			transaction.add(viewPager.getId(), fragmentList.get(0),
					tagString[0]);
		}
		if (!fragmentList.get(1).isAdded()) {
			transaction.add(viewPager.getId(), fragmentList.get(1),
					tagString[1]);
		}
		if (!fragmentList.get(2).isAdded()) {
			transaction.add(viewPager.getId(), fragmentList.get(2),
					tagString[2]);
		}

		if (!transaction.isEmpty()) {
			transaction.commit();
			fragment.getChildFragmentManager().executePendingTransactions();
		}
	}

	@Override
	public Fragment getItem(int position) {
		return fragmentList.get(position);
	}

	@Override
	protected String getTag(int position) {
		List<String> tagList = new ArrayList<String>();
		for (int i = 0; i < INFO_TAB_SIZE; i++) {
			tagList.add(tagString[i]);
		}

		return tagList.get(position);
	}

	@Override
	public int getCount() {
		return INFO_TAB_SIZE;
	}

}
